package com.cq.sphtech.net;

import android.util.Log;

import com.cq.sphtech.util.NetworkUtils;

import java.io.File;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.cq.sphtech.SPHTechApplication.getContext;
import static com.cq.sphtech.app.ApiConfig.APP_DOMAIN;

public class RestCreator {

    /**
     * 构建全局Retrofit客户端
     */
    private static final class RetrofitHolder {
        private static final Retrofit RETROFIT_ClIENT = new Retrofit.Builder()
                .baseUrl(APP_DOMAIN)//配置全局URL
                .client(OKHttpHolder.OK_HTTP_CLIENT)//拦截器
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private static final class OKHttpHolder {
        private static final int TIME_OUT = 60;
        private static final int cacheSize = 10 * 1024 * 1024;

        private static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder();

        private static OkHttpClient.Builder addInterceptor() {
            /**
             * 有网时候的缓存
             */
            final Interceptor NetCacheInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Response response = chain.proceed(request);
                    int onlineCacheTime = 30;//在线的时候的缓存过期时间，如果想要不缓存，直接时间设置为0
                    return response.newBuilder()
                            .header("Cache-Control", "public, max-age="+onlineCacheTime)
                            .removeHeader("Pragma")
                            .build();
                }
            };
            /**
             * 没有网时候的缓存
             */
            final Interceptor OfflineCacheInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (!NetworkUtils.isConnected(getContext())) {
                        int offlineCacheTime = 60;//离线的时候的缓存的过期时间
                        request = request.newBuilder()
//                        .cacheControl(new CacheControl
//                                .Builder()
//                                .maxStale(60,TimeUnit.SECONDS)
//                                .onlyIfCached()
//                                .build()
//                        ) 两种方式结果是一样的，写法不同
                                .header("Cache-Control", "public, only-if-cached, max-stale=" + offlineCacheTime)
                                .build();
                    }
                    return chain.proceed(request);
                }
            };

            /**
             * 请求日志拦截
             */
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    //打印retrofit日志
                    Log.i("RetrofitLog", "retrofitBack = " + message);
                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            BUILDER .addNetworkInterceptor(NetCacheInterceptor)
                    .addInterceptor(OfflineCacheInterceptor)
                    .cache(new Cache(new File(getContext().getExternalCacheDir().getAbsoluteFile(), "okhttpcache"), cacheSize))
                    .addInterceptor(loggingInterceptor);
            return BUILDER;
        }

        private static final OkHttpClient OK_HTTP_CLIENT = addInterceptor()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();
    }




    public static Retrofit getRxRestService() {
        return RetrofitHolder.RETROFIT_ClIENT;
    }
}
